package com.ruicar.afs.cloud.channel.blacklist.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruicar.afs.cloud.apply.admin.api.feign.ChannelOnlineSyncService;
import com.ruicar.afs.cloud.channel.affiliation.entity.ChannelAffiliatedUnitsRelTemp;
import com.ruicar.afs.cloud.channel.affiliation.entity.ChannelAffiliatedUnitsTemp;
import com.ruicar.afs.cloud.channel.affiliation.service.ChannelAffiliatedUnitsRelTempService;
import com.ruicar.afs.cloud.channel.affiliation.service.ChannelAffiliatedUnitsTempService;
import com.ruicar.afs.cloud.channel.blacklist.entity.BlacklistRelTemp;
import com.ruicar.afs.cloud.channel.blacklist.entity.BlacklistTemp;
import com.ruicar.afs.cloud.channel.blacklist.entity.DrawerPartyVo;
import com.ruicar.afs.cloud.channel.blacklist.service.BlacklistRelTempService;
import com.ruicar.afs.cloud.channel.blacklist.service.BlacklistTempService;
import com.ruicar.afs.cloud.channel.blacklist.utils.BlackDic;
import com.ruicar.afs.cloud.channel.blacklist.utils.BlackRelDic;
import com.ruicar.afs.cloud.channel.cardealer.entity.ChannelCoopeCardealerTemp;
import com.ruicar.afs.cloud.channel.cardealer.entity.CommonCarDealer;
import com.ruicar.afs.cloud.channel.cardealer.entity.DirectCarDealer;
import com.ruicar.afs.cloud.channel.cardealer.service.CarDealerService;
import com.ruicar.afs.cloud.channel.cardealer.service.ChannelCoopeCardealerService;
import com.ruicar.afs.cloud.channel.cardealer.service.DirectCarDealerService;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskAssign;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskCreated;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskDetail;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskAssignService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskCreatedService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskDetailService;
import com.ruicar.afs.cloud.channel.common.dto.BlackDTO;
import com.ruicar.afs.cloud.channel.common.dto.BlackToListDTO;
import com.ruicar.afs.cloud.channel.common.enums.ChannelAfsFlowEnum;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.feign.ListBaseFeign;
import com.ruicar.afs.cloud.channel.common.mq.sender.CaseAffiliationRelSender;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.CaseAffiliationRelSenderImpl;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.online.entity.ChannelBaseInfoTemp;
import com.ruicar.afs.cloud.channel.online.feign.ApplyFeignService;
import com.ruicar.afs.cloud.channel.online.service.ChannelOnlineService;
import com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants;
import com.ruicar.afs.cloud.channel.register.condition.SubmitDTO;
import com.ruicar.afs.cloud.channel.witness.entity.ChannelWitnessInfoTemp;
import com.ruicar.afs.cloud.channel.witness.service.ChannelWitnessInfoTempService;
import com.ruicar.afs.cloud.channel.witness.utils.WitnessDic;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.dto.ChannelCardDTO;
import com.ruicar.afs.cloud.common.modules.dto.mq.affiliation.AffiliationRelInfo;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.QueryFLowCmdRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.TaskSubmitRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.response.FlowCmdBean;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.*;


/**
 * @Author Ice
 * @Date 2020/05/27
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/black")
@Api(value = "black", description = "黑名单管理模块")
public class BlacklistTempController {
    private static final Logger logger = LoggerFactory.getLogger(BlacklistTempController.class);
    private final ListBaseFeign listBaseFeign;
    private ChannelConfig channelConfig;


    private final BlacklistTempService blacklistTempService;
    private final BlacklistRelTempService blacklistRelTempService;
    private final ChannelOnlineService channelOnlineService;
    private final ChannelAffiliatedUnitsTempService channelAffiliatedUnitsTempService;
    private final ChannelWitnessInfoTempService channelWitnessInfoTempService;
    private final ChannelUseCaseService channelUseCaseService;
    private final DirectCarDealerService directCarDealerService;
    private final ApplyFeignService applyFeignService;
    private ChannelOnlineSyncService channelOnlineSyncService;
    private ChannelCoopeCardealerService channelCoopeCardealerService;

    private final CarDealerService carDealerService;

    private final WorkTaskDetailService workTaskDetailService;
    private final UidGenerator uidGenerator;
    private final WorkflowService workflowService;
    private final WorkTaskAssignService workTaskAssignService;
    private final WorkTaskCreatedService workTaskCreatedService;
    private final ChannelAffiliatedUnitsRelTempService channelAffiliatedUnitsRelTempService;
    private final CaseAffiliationRelSenderImpl caseAffiliationRelSenderService;
    private final CaseAffiliationRelSender caseAffiliationRelSender;

    @PostMapping("/getBlackList")
    @ApiOperation(value = "查询数据")
    public IResponse<IPage<BlacklistTemp>> getBlackList(@RequestBody JSONObject json) {
        Integer pageNumber = json.getInteger("pageNumber");
        Integer pageSize = json.getInteger("pageSize");
        String blackName = json.getString("blackName");
        String blacklistType = json.getString("blacklistType");
        String carDealers = json.getString("carDealers");
        String idCode = json.getString("idCode");
        if (blacklistType == null || blacklistType == "") {
            return IResponse.fail("请选择黑名单类型！");
        }

        IPage<BlacklistTemp> list = blacklistTempService.page(new Page(pageNumber, pageSize), Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getBlacklistType, blacklistType).eq(BlacklistTemp::getWeatherBlacklist, BlackDic.WEATHER_BLACKLIST_YES).eq(BlacklistTemp::getStatus, BlackDic.STATUS_PASS).eq(StringUtils.isNoneEmpty(carDealers), BlacklistTemp::getCarDealers, carDealers).like(StringUtils.isNotEmpty(blackName), BlacklistTemp::getBlackName, blackName).like(StringUtils.isNoneEmpty(idCode), BlacklistTemp::getIdCode, idCode).orderByDesc(BlacklistTemp::getBlackDate));

        return IResponse.success(list);
    }

    @PostMapping("/getApproveList")
    @ApiOperation(value = "查询数据")
    public IResponse<IPage<BlacklistTemp>> getApproveList(@RequestBody JSONObject json) {
        Integer pageNumber = json.getInteger("pageNumber");
        Integer pageSize = json.getInteger("pageSize");
        String blackName = json.getString("blackName");
        String blacklistType = json.getString("blacklistType");
        String carDealers = json.getString("carDealers");
        String idCode = json.getString("idCode");
        if (blacklistType == null || blacklistType == "") {
            return IResponse.fail("请选择黑名单类型！");
        }

        // 查询自己的
        String userName = SecurityUtils.getUsername();
        Page page = new Page(pageNumber, pageSize);
        IPage<List<BlacklistTemp>> list = blacklistTempService.getRegister(page, blackName, blacklistType, carDealers, idCode, userName, AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_BLACK_JOIN));
        // 先去查询 待审批的数据信息
//        List<Long> ids =blacklistTempService.getBlackListIds(userName,AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_BLACK_JOIN),AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_BLACK_RELIEVE));
//
//        IPage<BlacklistTemp> list = blacklistTempService.page(new Page(pageNumber,pageSize), Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getBlacklistType,blacklistType).eq(StringUtils.isNoneEmpty(carDealers),BlacklistTemp::getCarDealers,carDealers).like(StringUtils.isNotEmpty(blackName),BlacklistTemp::getBlackName,blackName).like(StringUtils.isNoneEmpty(idCode),BlacklistTemp::getIdCode,idCode).in(BlacklistTemp::getId,ids));

        return IResponse.success(list);
    }

    @ApiOperation(value = "通过id，申请解除黑名单")
    @RequestMapping(value = "/removeBlacklist", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public IResponse upStatus(@RequestBody BlacklistTemp black) throws JsonProcessingException {
        if (black.getId() == null) {
            return IResponse.fail("请选择要申请的黑名单！");
        }
        BlacklistTemp bb =blacklistTempService.getById(black);
        this.relieveBlack(bb);
        return new IResponse<Boolean>().setMsg("申请成功！");
    }
    // 解除申请黑名单
    @Transactional
    public void relieveBlack(BlacklistTemp black){
        BlacklistTemp bb = blacklistTempService.getById(black);


        // 这个是只为见证人用的用于停系统账号
        List<ChannelCardDTO> upIds = new ArrayList<>();

        // 创建一个集合，存要修改的id
        List<Long> ids = new ArrayList<>();
        IResponse result = new IResponse();

        // 创建一个数据传输报头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
            // 第二部看看有没有关联关系
            List<BlacklistRelTemp> list = blacklistRelTempService.list(Wrappers.<BlacklistRelTemp>query().lambda().eq(BlacklistRelTemp::getBlacklistId, bb.getId()));

            // 如何是合作商
            if (BlackDic.BLACKLIST_TYPE_PARTNER.equals(bb.getBlacklistType())) {

                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ChannelBaseInfoTemp temp = channelOnlineService.getById(list.get(i).getBlacklistTypeId());
                        temp.setChannelStatus(list.get(i).getStatus());
                        temp.setChannelStatusOldCar(list.get(i).getChannelStatusOldCar());
                        channelOnlineService.updateById(temp);
                        // 只有以前的状态是 启用或者审核中才会去案件同步
                        if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getBlacklistTypeId());
                        }
                    }
                    // 去修改案件那边数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusByChannelPass(ids, headers);
                    }
                }
            }
            // 如果是挂靠单位
            if (BlackDic.BLACKLIST_TYPE_COMPANY.equals(bb.getBlacklistType())) {
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ChannelAffiliatedUnitsTemp temp = channelAffiliatedUnitsTempService.getById(list.get(i).getBlacklistTypeId());
                        temp.setStatus(list.get(i).getStatus());
                        channelAffiliatedUnitsTempService.updateById(temp);
                        // 只有以前的状态是 启用或者审核中才会去案件同步
                        if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getBlacklistTypeId());
                        }
                    }
                    // 去修改案件那边数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upDateCaseStatusByIdsPass(ids, headers);
                    }
                }
            }
            // 如果是见证人
            if (BlackDic.BLACKLIST_TYPE_WITNESS.equals(bb.getBlacklistType())) {
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ChannelWitnessInfoTemp temp = channelWitnessInfoTempService.getById(list.get(i).getBlacklistTypeId());
                        temp.setStatus(list.get(i).getStatus());
                        channelWitnessInfoTempService.updateById(temp);

                        ChannelCardDTO dto = new ChannelCardDTO();
                        dto.setCard(temp.getWitnessIdCard());
                        dto.setChannelId(temp.getChannelId());
                        upIds.add(dto);

                        // 只有以前的状态是 启用或者审核中才会去案件同步
                        if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getBlacklistTypeId());
                        }
                    }
                    // 去修改案件那边数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusWitnessByChannelIdsPass(ids, headers);
                    }

                    // 被关掉的账号给启用了
                    Map<String, String> requestHeader = new HashMap<>();
                    requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
                    requestHeader.put("clientSecret", channelConfig.getApplyAdminClientSecret());
                    IResponse res = channelOnlineSyncService.startWitnessInfo(upIds, requestHeader);

                }
            }

            // 如果是开票方
            if (BlackDic.BLACKLIST_TYPE_BILLING.equals(bb.getBlacklistType())) {
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ids.add(list.get(i).getBlacklistTypeId());
                    }
                    // 去修改案件那边数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusDrawerByChannelIdsPass(ids, headers);
                    }
                }
            }


            // 如果是车商
            if (BlackDic.BLACKLIST_TYPE_CAR_DEALER.equals(bb.getBlacklistType())) {
                // 判断是直营车商还是普通车商
                if (BlackDic.CAR_DEALERS_ORDINARY.equals(bb.getCarDealers())) {
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            // 只有以前的状态是 启用或者审核中才会去案件同步
                            if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                                ids.add(list.get(i).getBlacklistTypeId());
                            }
                            CommonCarDealer temp = carDealerService.getById(list.get(i).getBlacklistTypeId());
                            temp.setStatus(list.get(i).getStatus());
                            carDealerService.updateById(temp);
                        }
                        // 去修改案件那边数据
                        if (ids.size() > 0) {
                            result = channelUseCaseService.upStatusCarDealerByChannelIdsPass(ids, headers);
                        }
                    }

                } else if (BlackDic.CAR_DEALERS_DIRECT.equals(bb.getCarDealers())) {
                    // 这边是直营车商
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            ChannelBaseInfoTemp temp = channelOnlineService.getById(list.get(i).getBlacklistTypeId());
                            temp.setChannelStatus(list.get(i).getStatus());
                            temp.setChannelStatusOldCar(list.get(i).getChannelStatusOldCar());
                            channelOnlineService.updateById(temp);
                            // 只有以前的状态是 启用或者审核中才会去案件同步
                            if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                                ids.add(list.get(i).getBlacklistTypeId());
                            }
                        }
                        // 去修改案件那边数据
                        if (ids.size() > 0) {
                            result = channelUseCaseService.upStatusByChannelPass(ids, headers);
                        }
                    }

                }

            }


            //最后把关系数据给删除
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    blacklistRelTempService.remove(Wrappers.<BlacklistRelTemp>query().lambda().eq(BlacklistRelTemp::getId, list.get(i).getId()));
                }
            }

            // 更新名单库数据
            BlacklistTemp temp = blacklistTempService.getById(bb.getId());
            BlackToListDTO btc = new BlackToListDTO();
            BlackDTO condition = new BlackDTO();
            condition.setStatus("2");
            // 赋值名单类型：合作商 01、挂靠单位 02、⻋商 05、⻅证⼈ 03、开票⽅ 04
            condition.setType(temp.getBlacklistType());
            condition.setName(temp.getBlackName());
            // 证件号码
            condition.setCertificateNo(temp.getIdCode());
            // 给证件类型（身份证 01、统⼀信⽤代码 02、纳税⼈识别号 03
            condition.setCertificateType(temp.getIdType());
            condition.setDeadTime(new Date(System.currentTimeMillis()));
            condition.setReason(temp.getRelieveReason());
            condition.setApiUser("apiUser");
            // 仅车商可用⻋：商类型(1为普通⻋商2为直营⻋商)
            if (BlackDic.CAR_DEALERS_ORDINARY.equals(temp.getCarDealers())) {
                condition.setDealerType("1");
            } else if (BlackDic.CAR_DEALERS_DIRECT.equals(temp.getCarDealers())) {
                condition.setDealerType("2");
            }
            btc.setData(condition);
            JSONObject json = listBaseFeign.upBlackList(btc);
            if ("200".equals(json.get("code").toString())) {

            } else {
                throw new AfsBaseException("更新名单库失败！");
            }
        blacklistTempService.remove(Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getId, bb.getId()));

    }

    @Transactional
    @PostMapping("/save")
    @ApiOperation(value = "保存数据")
    public IResponse save(@RequestBody BlacklistTemp blacklistTemp) throws ParseException, JsonProcessingException {
        List<BlacklistTemp> list = new ArrayList<>();
        if(BlackDic.BLACKLIST_TYPE_CAR_DEALER.equals(blacklistTemp.getIdType())){
            list= blacklistTempService.list(Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getIdCode, blacklistTemp.getIdCode()).eq(BlacklistTemp::getBlacklistType,blacklistTemp.getBlacklistType()).eq(BlacklistTemp::getCarDealers,blacklistTemp.getCarDealers()));
        }else {
            list= blacklistTempService.list(Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getIdCode, blacklistTemp.getIdCode()).eq(BlacklistTemp::getBlacklistType,blacklistTemp.getBlacklistType()));
        }

        if (list.size() > 0) {
            if (BlackDic.STATUS_STOP.equals(list.get(0).getStatus())) {
                return IResponse.fail("这个客户已解除黑名单，请前往修改！");
            } else {
                return IResponse.fail("这个客户已在审核或者已加入黑名单无需重复申请！");
            }

        }
        blacklistTemp.setExamineStatus(BlackDic.EXAMINE_STATUS_INTO);
        blacklistTemp.setWeatherBlacklist(BlackDic.WEATHER_BLACKLIST_NO);
        blacklistTemp.setStatus(BlackDic.STATUS_APPROVE);
        blacklistTemp.setCreateBy(SecurityUtils.getUsername());
        blacklistTemp.setCreateTime(new Date(System.currentTimeMillis()));
        blacklistTemp.setDelFlag(BlackDic.DEL_FLAG_USABLE);
        blacklistTemp.setStatus(BlackDic.STATUS_PASS);
        blacklistTempService.save(blacklistTemp);
        // 发起工作流
       //  this.foundWorkFlow(blacklistTemp);
        this.joinBlack(blacklistTemp);
        return IResponse.success("保存成功").setData(blacklistTemp);
    }
    // 加入黑名单
    public void joinBlack(BlacklistTemp bb){
        bb.setStatus(BlackDic.STATUS_PASS);
        bb.setWeatherBlacklist(BlackDic.WEATHER_BLACKLIST_YES);
        bb.setBlackDate(new Date(System.currentTimeMillis()));
        bb.setExamineStatus(BlackDic.EXAMINE_STATUS_PASS);
        bb.setUpdateBy(SecurityUtils.getUsername());
        bb.setUpdateTime(new Date(System.currentTimeMillis()));
        blacklistTempService.updateById(bb);
        BlacklistTemp black = blacklistTempService.getById(bb.getId());
        // 创建一个数据传输报头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());

        // 声明一个空的数组
        List<Long> ids = new ArrayList<>();
        // 这个是只为见证人用的用于停系统账号
        List<ChannelCardDTO> upIds = new ArrayList<>();

        IResponse result = new IResponse();
            // 如何是合作商
            if (BlackDic.BLACKLIST_TYPE_PARTNER.equals(black.getBlacklistType())) {
                // 查询这个合作商的信息
                List<ChannelBaseInfoTemp> list = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getSocUniCrtCode, black.getIdCode()).eq(ChannelBaseInfoTemp::getChannelType, ChannelOnlineConstants.CHANNEL_TYPE_CHANNEL));
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        // 存储被拉黑的这个信息到关联表
                        BlacklistRelTemp relTemp = new BlacklistRelTemp();
                        relTemp.setBlacklistId(black.getId());
                        relTemp.setBlacklistTypeId(list.get(i).getId());
                        relTemp.setStatus(list.get(i).getChannelStatus());
                        relTemp.setChannelStatusOldCar(list.get(i).getChannelStatusOldCar());
                        blacklistRelTempService.save(relTemp);

                        // 把这条信息停用
                        list.get(i).setChannelStatus(BlackDic.STATUS_STOP);
                        list.get(i).setChannelStatusOldCar(BlackDic.STATUS_STOP);
                        channelOnlineService.updateById(list.get(i));

                        // 给数组里面加数据
                        ids.add(list.get(i).getId());
                    }
                    // 再去案件那边去停用
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusByChannel(ids, headers);

                        // 去进件停账号
                        Map<String, String> requestHeader = new HashMap<>();
                        requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
                        requestHeader.put("clientSecret", channelConfig.getApplyAdminClientSecret());
                        channelOnlineSyncService.stopChannel(ids, requestHeader);
                    }


                }
            }
            // 判断如果是挂靠单位
            if (BlackDic.BLACKLIST_TYPE_COMPANY.equals(black.getBlacklistType())) {
                List<ChannelAffiliatedUnitsTemp> list = channelAffiliatedUnitsTempService.list(Wrappers.<ChannelAffiliatedUnitsTemp>query().lambda().eq(ChannelAffiliatedUnitsTemp::getSocUniCrtCode, black.getIdCode()));
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        // 给数组里面加数据,并且只有在当时状态是  启用或者审核中
                        if (WitnessDic.STATUS_PASS.equals(list.get(i).getStatus()) || WitnessDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getId());

                        }
                        // 存储被拉黑的这个信息到关联表
                        BlacklistRelTemp relTemp = new BlacklistRelTemp();
                        relTemp.setBlacklistId(black.getId());
                        relTemp.setBlacklistTypeId(list.get(i).getId());
                        relTemp.setStatus(list.get(i).getStatus());
                        blacklistRelTempService.save(relTemp);

                        // 把这个挂靠公司停用
                        list.get(i).setStatus(BlackDic.STATUS_STOP);
                        channelAffiliatedUnitsTempService.updateById(list.get(i));
                        List<ChannelAffiliatedUnitsRelTemp> channelAffiliatedUnitsRelTemps=channelAffiliatedUnitsRelTempService.list(Wrappers.<ChannelAffiliatedUnitsRelTemp>query().lambda().eq(ChannelAffiliatedUnitsRelTemp::getArriliatedId,list.get(i).getId()));
                        for(ChannelAffiliatedUnitsRelTemp channelAffiliatedUnitsRelTemp:channelAffiliatedUnitsRelTemps){
                            channelAffiliatedUnitsRelTemp.setStatus(BlackDic.STATUS_STOP);
                            channelAffiliatedUnitsRelTempService.updateById(channelAffiliatedUnitsRelTemp);
                        }
                        AfsTransEntity<AffiliationRelInfo> transEntity = this.caseAffiliationRelSenderService.returnAffiliationRelInfo(list.get(i).getId().toString());
                        log.info("挂靠及合作商信息……", transEntity);
                        caseAffiliationRelSender.pushInfoToCaeAffiliation(transEntity);
                    }
                }
            }
            // 判断如果是见证人
            if (BlackDic.BLACKLIST_TYPE_WITNESS.equals(black.getBlacklistType())) {
                List<ChannelWitnessInfoTemp> list = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, black.getIdCode()).notIn(ChannelWitnessInfoTemp::getStatus, WitnessDic.STATUS_STOP));
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ChannelCardDTO dto = new ChannelCardDTO();
                        dto.setCard(list.get(i).getWitnessIdCard());
                        dto.setChannelId(list.get(i).getChannelId());
                        upIds.add(dto);
                        // 给数组里面加数据,并且只有在当时状态是  启用或者审核中
                        if (WitnessDic.STATUS_PASS.equals(list.get(i).getStatus()) || WitnessDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getId());
                        }
                        // 存储被拉黑的这个信息到关联表
                        BlacklistRelTemp relTemp = new BlacklistRelTemp();
                        relTemp.setBlacklistId(black.getId());
                        relTemp.setBlacklistTypeId(list.get(i).getId());
                        relTemp.setStatus(list.get(i).getStatus());
                        blacklistRelTempService.save(relTemp);

                        list.get(i).setStatus(BlackDic.STATUS_STOP);
                        channelWitnessInfoTempService.updateById(list.get(i));


                    }

                    // 记得修改案件那边的数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusWitnessByChannelIds(ids, headers);
                    }

                    // 停用见证人账号
                    Map<String, String> requestHeader = new HashMap<>();
                    requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
                    requestHeader.put("clientSecret", channelConfig.getApplyAdminClientSecret());
                    IResponse res = channelOnlineSyncService.stopWitnessByBlack(upIds, requestHeader);
                }
            }

            //判断如果是开票方
            if (BlackDic.BLACKLIST_TYPE_BILLING.equals(black.getBlacklistType())) {

                IResponse a = channelUseCaseService.getDrawerPartyByIdType(blacklistTempService.getById(black.getId()), headers);
                if ("0000".equals(a.getCode())) {
                    String listTxt = JSONArray.toJSONString(a.getData());
                    List<DrawerPartyVo> list = JSONArray.parseArray(listTxt, DrawerPartyVo.class);
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            BlacklistRelTemp relTemp = new BlacklistRelTemp();
                            relTemp.setBlacklistId(black.getId());
                            relTemp.setBlacklistTypeId(list.get(i).getId());
                            relTemp.setStatus(list.get(i).getStatus());
                            relTemp.setCreateBy(SecurityUtils.getUsername());
                            relTemp.setCreateTime(new Date(System.currentTimeMillis()));
                            blacklistRelTempService.save(relTemp);
                        }
                    }
                }
            }
            // 判断如果是车商
            if (BlackDic.BLACKLIST_TYPE_CAR_DEALER.equals(black.getBlacklistType())) {
                // 判断是直营车商还是普通车商
                if (BlackDic.CAR_DEALERS_ORDINARY.equals(black.getCarDealers())) {
                    // 普通车商进来
                    List<CommonCarDealer> list = carDealerService.list(Wrappers.<CommonCarDealer>query().lambda().eq(CommonCarDealer::getSocUniCrtCode, black.getIdCode()));
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            // 给数组里面加数据,并且只有在当时状态是  启用或者审核中
                            if (WitnessDic.STATUS_PASS.equals(list.get(i).getStatus()) || WitnessDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                                ids.add(list.get(i).getId());
                            }
                            BlacklistRelTemp relTemp = new BlacklistRelTemp();
                            relTemp.setBlacklistId(black.getId());
                            relTemp.setBlacklistTypeId(list.get(i).getId());
                            relTemp.setStatus(list.get(i).getStatus());
                            relTemp.setCreateBy(SecurityUtils.getUsername());
                            relTemp.setCreateTime(new Date(System.currentTimeMillis()));
                            blacklistRelTempService.save(relTemp);

                            // 修改表的状态
                            list.get(i).setStatus(BlackDic.STATUS_STOP);
                            carDealerService.updateById(list.get(i));
                            //停用关联表中关联关系
                            List<ChannelCoopeCardealerTemp> cardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                                    .eq(ChannelCoopeCardealerTemp::getCardealerId, list.get(i).getId().toString())
                                    .eq(ChannelCoopeCardealerTemp::getCardealerType, BlackDic.CAR_DEALERS_ORDINARY)
                            );
                            if (cardealerTemps.size() > 0) {
                                for (ChannelCoopeCardealerTemp temp : cardealerTemps) {
                                    temp.setStatus(BlackDic.STATUS_STOP);
                                    channelCoopeCardealerService.updateById(temp);
                                }
                            }
                        }
                        // 停用案件那边的信息状态
                        if (ids.size() > 0) {
                            result = channelUseCaseService.upStatusCarDealerByChannelIds(ids, headers);
                        }
                    }

                } else if (BlackDic.CAR_DEALERS_DIRECT.equals(black.getCarDealers())) {
                    // 直营车商进来
                    List<DirectCarDealer> list = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                            .eq(DirectCarDealer::getSocUniCrtCode, black.getIdCode())
                            .eq(DirectCarDealer::getChannelType, ChannelOnlineConstants.CHANNEL_TYPE_CAR_DEALERS));
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            BlacklistRelTemp relTemp = new BlacklistRelTemp();
                            relTemp.setBlacklistId(black.getId());
                            relTemp.setBlacklistTypeId(list.get(i).getId());
                            relTemp.setStatus(list.get(i).getChannelStatus());
                            relTemp.setChannelStatusOldCar(list.get(i).getChannelStatusOldCar());
                            relTemp.setCreateBy(SecurityUtils.getUsername());
                            relTemp.setCreateTime(new Date(System.currentTimeMillis()));
                            blacklistRelTempService.save(relTemp);


                            // 把这条信息停用
                            if (list.get(i).getChannelStatus() != null) {
                                list.get(i).setChannelStatus(BlackDic.STATUS_STOP);
                            }
                            if (list.get(i).getChannelStatusOldCar() != null) {
                                list.get(i).setChannelStatusOldCar(BlackDic.STATUS_STOP);
                            }
                            directCarDealerService.updateById(list.get(i));

                            //停用关联表中关联关系
                            List<ChannelCoopeCardealerTemp> cardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                                    .eq(ChannelCoopeCardealerTemp::getCardealerId, list.get(i).getId().toString())
                                    .eq(ChannelCoopeCardealerTemp::getCardealerType, BlackDic.CAR_DEALERS_DIRECT)
                            );
                            if (cardealerTemps.size() > 0) {
                                for (ChannelCoopeCardealerTemp temp : cardealerTemps) {
                                    temp.setStatus(BlackDic.STATUS_STOP);
                                    channelCoopeCardealerService.updateById(temp);
                                }
                            }

                            // 给数组里面加数据
                            ids.add(list.get(i).getId());
                        }
                        // 再去案件那边去停用
                        if (ids.size() > 0) {
                            result = channelUseCaseService.upStatusByChannel(ids, headers);
                        }
                    }

                }


            }
            // 更新到名单库
            BlacklistTemp temp = blacklistTempService.getById(black.getId());
            BlackToListDTO btc = new BlackToListDTO();
            BlackDTO condition = new BlackDTO();
            condition.setStatus("1");
            // 赋值名单类型：合作商 01、挂靠单位 02、⻋商 05、⻅证⼈ 03、开票⽅ 04
            condition.setType(temp.getBlacklistType());
            condition.setName(temp.getBlackName());
            // 证件号码
            condition.setCertificateNo(temp.getIdCode());
            // 给证件类型（身份证 01、统⼀信⽤代码 02、纳税⼈识别号 03
            condition.setCertificateType(temp.getIdType());
            condition.setJoinTime(new Date(System.currentTimeMillis()));
            condition.setReason(temp.getBlacklistReason());
            condition.setApiUser("apiUser");
            // 仅车商可用⻋：商类型(1为普通⻋商2为直营⻋商)
            if (BlackDic.CAR_DEALERS_ORDINARY.equals(temp.getCarDealers())) {
                condition.setDealerType("1");
            } else if (BlackDic.CAR_DEALERS_DIRECT.equals(temp.getCarDealers())) {
                condition.setDealerType("2");
            }
            btc.setData(condition);
            JSONObject json = listBaseFeign.upBlackList(btc);
            if ("200".equals(json.get("code").toString())) {

            } else {
                throw new AfsBaseException("更新名单库失败！");
            }


    }

    public void foundWorkFlow(BlacklistTemp temp) throws JsonProcessingException {
        StartFlowRequest startFlowNew = new StartFlowRequest();
        startFlowNew.setAfsFlowKey(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_BLACK_JOIN));
        startFlowNew.setBizDataId(uidGenerator.getUID() + "");
        startFlowNew.setFlowName((StringUtils.isEmpty(temp.getBlackName())?"":(temp.getBlackName())+"-")+AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_BLACK_JOIN));
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(temp);
        JSONObject cancelJson = JSONObject.parseObject(json);
        workflowService.startWorkFlow(startFlowNew, cancelJson);
        //保存业务相关数据、用户前端逻辑判断
        WorkTaskDetail detail = new WorkTaskDetail();
        detail.setBizDataId(startFlowNew.getBizDataId());
        detail.setName(temp.getBlackName());
        detail.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_BLACK_JOIN));
        //黑名单id绑定
        detail.setBusinessKey(temp.getId());
        workTaskDetailService.save(detail);
        // 给这个条数据绑定流程id
        temp.setDataId(Long.valueOf(startFlowNew.getBizDataId()));
        blacklistTempService.updateById(temp);
    }

    public void submit(SubmitDTO dto) throws JsonProcessingException {
        WorkTaskAssign assgin = workTaskAssignService.getOne(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, dto.getBizDataId())
                .eq(WorkTaskAssign::getUserName, SecurityUtils.getUsername()));
        WorkTaskCreated created = workTaskCreatedService.getOne(Wrappers.<WorkTaskCreated>query().lambda().eq(WorkTaskCreated::getBizDataId, dto.getBizDataId()));
        WorkTaskDetail detail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBizDataId, dto.getBizDataId()));
        //提交完成之后删除其他人员代办
        List<WorkTaskAssign> assignList = workTaskAssignService.list(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, dto.getBizDataId()));

        TaskSubmitRequest taskSubmitRequest = new TaskSubmitRequest();
        taskSubmitRequest.setGwtUserId(assgin.getAssignId());
        taskSubmitRequest.setAfsFlowKey(created.getAfsFlowKey());
        taskSubmitRequest.setBizDataId(created.getBizDataId());
        QueryFLowCmdRequest request = new QueryFLowCmdRequest();
        request.setFlowInstanceId(created.getFlowInstanceId());
        WorkFlowResponse<List<FlowCmdBean>> cmdResponse = workflowService.queryFlowCmd(request);
        List<FlowCmdBean> cmdList = cmdResponse.getAfsData();
        FlowCmdBean cmd = workTaskCreatedService.channelApprove(dto.getApprove(), cmdList);

        BlacklistTemp temp = blacklistTempService.getById(dto.getRegisterId());
        if (cmd != null) {
            log.info("==================================提交工作流开始==================================》");
            taskSubmitRequest.setCmdId(cmd.getId());
            ObjectMapper mapper = new ObjectMapper();
            //获取配置节点信息
            String json = mapper.writeValueAsString(temp);
            JSONObject cancelJson = JSONObject.parseObject(json);
            workflowService.taskSubmit(taskSubmitRequest, cancelJson);

            //删除剩余节点数据信息
            for (int i = 0; i < assignList.size(); i++) {
                workTaskAssignService.removeById(assignList.get(i).getId().toString());
            }
        } else {
            throw new AfsBaseException("提交工作流失败！");
        }
    }

    @PostMapping("/checkBlack")
    @ApiOperation(value = "校验黑名单")
    public Object checkBlack(@RequestBody BlacklistTemp black) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (black.getBlacklistType() == "" || black.getBlacklistType() == null || black.getIdCode() == null || black.getIdCode() == "") {
                throw new AfsBaseException("请完善信息！");
            }
            BlackDTO condition = new BlackDTO();
            condition.setPageNum(1);
            condition.setPageSize(10);
            condition.setCertificateNo(black.getIdCode());
            condition.setType(black.getBlacklistType());
            condition.setStatus("1");
            JSONObject json = listBaseFeign.getBlackList(condition);

            if ("200".equals(json.get("code").toString())) {
                Integer total = json.getInteger("total");
                if (total > 0) {
                    resultMap.put("weatherBlackList", BlackDic.WEATHER_BLACKLIST_YES);
                } else {
                    resultMap.put("weatherBlackList", BlackDic.WEATHER_BLACKLIST_NO);
                }
                resultMap.put("code", "0000");
                resultMap.put("msg", "success");
            }
        } catch (Exception e) {
            resultMap.put("code", "9999");
            resultMap.put("msg", "查询失败，请联系管理员！");
            logger.error(e.getMessage(), e);
        }

        return resultMap;
    }

    @PostMapping("/checkNewBlack")
    @ApiOperation(value = "名单库校验黑名单")
    public Object checkNewBlack(@RequestBody BlacklistTemp black) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (black.getBlacklistType() == "" || black.getBlacklistType() == null || black.getIdCode() == null || black.getIdCode() == "") {
                throw new AfsBaseException("请完善信息！");
            }
            BlackDTO condition = new BlackDTO();
            condition.setPageNum(1);
            condition.setPageSize(10);
            condition.setCertificateNo(black.getIdCode());
            condition.setType(black.getBlacklistType());
            condition.setStatus("1");
            JSONObject json = listBaseFeign.getBlackList(condition);

            if ("200".equals(json.get("code").toString())) {
                Integer total = json.getInteger("total");
                if (total > 0) {
                    resultMap.put("weatherBlackList", BlackDic.WEATHER_BLACKLIST_YES);
                } else {
                    resultMap.put("weatherBlackList", BlackDic.WEATHER_BLACKLIST_NO);
                }
                resultMap.put("code", "0000");
                resultMap.put("msg", "success");
            } else {
                resultMap.put("code", "9999");
                resultMap.put("msg", "查询失败，请联系管理员！");
                throw new AfsBaseException("名单库黑名单查询失败！");
            }

        } catch (Exception e) {
            resultMap.put("code", "9999");
            resultMap.put("msg", "查询失败，请联系管理员！");
            logger.error(e.getMessage(), e);
        }
        return resultMap;
    }

    @Transactional
    @PostMapping("/blackApplyExamine")
    @ApiOperation(value = "黑名单申请审核")
    public IResponse blackApplyExamine(@RequestBody BlacklistTemp bb) throws JsonProcessingException {
        BlacklistTemp b = blacklistTempService.getById(bb.getId());
        if (!BlackDic.STATUS_APPROVE.equals(b.getStatus())) {
            throw new AfsBaseException("信息已被审核！");
        }
        if (BlackDic.STATUS_REFUSE.equals(bb.getStatus())) {
            // 先结束工作流
            // 这边进来是拒绝
            SubmitDTO dto = new SubmitDTO();
            dto.setRegisterId(bb.getId());
            dto.setApprove("3");
            dto.setBizDataId(b.getDataId().toString());

            submit(dto);
            // 说明被拒绝了，直接删除了好吧
            blacklistTempService.remove(Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getId, bb.getId()));
            return IResponse.success("操作成功！").setData("");
        }
        //第一步先更新这个黑名单的数据
        bb.setWeatherBlacklist(BlackDic.WEATHER_BLACKLIST_YES);
        bb.setBlackDate(new Date(System.currentTimeMillis()));
        bb.setExamineStatus(BlackDic.EXAMINE_STATUS_PASS);
        bb.setUpdateBy(SecurityUtils.getUsername());
        bb.setUpdateTime(new Date(System.currentTimeMillis()));
        blacklistTempService.updateById(bb);
        BlacklistTemp black = blacklistTempService.getById(bb.getId());
        // 第二步 黑名单存公司名单库


        // 创建一个数据传输报头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());

        // 声明一个空的数组
        List<Long> ids = new ArrayList<>();
        // 这个是只为见证人用的用于停系统账号
        List<ChannelCardDTO> upIds = new ArrayList<>();

        IResponse result = new IResponse();

        // 再判断这个状态是什么，如果是通过那么需要做关系处理
        if (BlackDic.STATUS_PASS.equals(black.getStatus())) {
            // 如何是合作商
            if (BlackDic.BLACKLIST_TYPE_PARTNER.equals(black.getBlacklistType())) {
                // 查询这个合作商的信息
                List<ChannelBaseInfoTemp> list = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getSocUniCrtCode, black.getIdCode()).eq(ChannelBaseInfoTemp::getChannelType, ChannelOnlineConstants.CHANNEL_TYPE_CHANNEL));
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        // 存储被拉黑的这个信息到关联表
                        BlacklistRelTemp relTemp = new BlacklistRelTemp();
                        relTemp.setBlacklistId(black.getId());
                        relTemp.setBlacklistTypeId(list.get(i).getId());
                        relTemp.setStatus(list.get(i).getChannelStatus());
                        relTemp.setChannelStatusOldCar(list.get(i).getChannelStatusOldCar());
                        blacklistRelTempService.save(relTemp);

                        // 把这条信息停用
                        list.get(i).setChannelStatus(BlackDic.STATUS_STOP);
                        list.get(i).setChannelStatusOldCar(BlackDic.STATUS_STOP);
                        channelOnlineService.updateById(list.get(i));

                        // 给数组里面加数据
                        ids.add(list.get(i).getId());
                    }
                    // 再去案件那边去停用
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusByChannel(ids, headers);

                        // 去进件停账号
                        Map<String, String> requestHeader = new HashMap<>();
                        requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
                        requestHeader.put("clientSecret", channelConfig.getApplyAdminClientSecret());
                        channelOnlineSyncService.stopChannel(ids, requestHeader);
                    }


                }
            }
            // 判断如果是挂靠单位
            if (BlackDic.BLACKLIST_TYPE_COMPANY.equals(black.getBlacklistType())) {
                List<ChannelAffiliatedUnitsTemp> list = channelAffiliatedUnitsTempService.list(Wrappers.<ChannelAffiliatedUnitsTemp>query().lambda().eq(ChannelAffiliatedUnitsTemp::getSocUniCrtCode, black.getIdCode()));
                if (list.size() > 0) {

                    for (int i = 0; i < list.size(); i++) {
                        // 给数组里面加数据,并且只有在当时状态是  启用或者审核中
                        if (WitnessDic.STATUS_PASS.equals(list.get(i).getStatus()) || WitnessDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getId());

                        }
                        // 存储被拉黑的这个信息到关联表
                        BlacklistRelTemp relTemp = new BlacklistRelTemp();
                        relTemp.setBlacklistId(black.getId());
                        relTemp.setBlacklistTypeId(list.get(i).getId());
                        relTemp.setStatus(list.get(i).getStatus());
                        blacklistRelTempService.save(relTemp);

                        // 把这个挂靠公司停用
                        list.get(i).setStatus(BlackDic.STATUS_STOP);
                        channelAffiliatedUnitsTempService.updateById(list.get(i));


                    }
                    // 把案件的那边同步一下
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusByChannelIds(ids, headers);
                    }


                }
            }
            // 判断如果是见证人
            if (BlackDic.BLACKLIST_TYPE_WITNESS.equals(black.getBlacklistType())) {
                List<ChannelWitnessInfoTemp> list = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, black.getIdCode()).notIn(ChannelWitnessInfoTemp::getStatus, WitnessDic.STATUS_STOP));
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ChannelCardDTO dto = new ChannelCardDTO();
                        dto.setCard(list.get(i).getWitnessIdCard());
                        dto.setChannelId(list.get(i).getChannelId());
                        upIds.add(dto);
                        // 给数组里面加数据,并且只有在当时状态是  启用或者审核中
                        if (WitnessDic.STATUS_PASS.equals(list.get(i).getStatus()) || WitnessDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getId());
                        }
                        // 存储被拉黑的这个信息到关联表
                        BlacklistRelTemp relTemp = new BlacklistRelTemp();
                        relTemp.setBlacklistId(black.getId());
                        relTemp.setBlacklistTypeId(list.get(i).getId());
                        relTemp.setStatus(list.get(i).getStatus());
                        blacklistRelTempService.save(relTemp);

                        list.get(i).setStatus(BlackDic.STATUS_STOP);
                        channelWitnessInfoTempService.updateById(list.get(i));


                    }

                    // 记得修改案件那边的数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusWitnessByChannelIds(ids, headers);
                    }

                    // 停用见证人账号
                    Map<String, String> requestHeader = new HashMap<>();
                    requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
                    requestHeader.put("clientSecret", channelConfig.getApplyAdminClientSecret());
                    IResponse res = channelOnlineSyncService.stopWitnessInfo(upIds, requestHeader);
                }
            }

            //判断如果是开票方
            if (BlackDic.BLACKLIST_TYPE_BILLING.equals(black.getBlacklistType())) {

                IResponse a = channelUseCaseService.getDrawerPartyByIdType(blacklistTempService.getById(black.getId()), headers);
                if ("0000".equals(a.getCode())) {
                    String listTxt = JSONArray.toJSONString(a.getData());
                    List<DrawerPartyVo> list = JSONArray.parseArray(listTxt, DrawerPartyVo.class);
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            BlacklistRelTemp relTemp = new BlacklistRelTemp();
                            relTemp.setBlacklistId(black.getId());
                            relTemp.setBlacklistTypeId(list.get(i).getId());
                            relTemp.setStatus(list.get(i).getStatus());
                            relTemp.setCreateBy(SecurityUtils.getUsername());
                            relTemp.setCreateTime(new Date(System.currentTimeMillis()));
                            blacklistRelTempService.save(relTemp);
                        }
                    }
                }
            }
            // 判断如果是车商
            if (BlackDic.BLACKLIST_TYPE_CAR_DEALER.equals(black.getBlacklistType())) {
                // 判断是直营车商还是普通车商
                if (BlackDic.CAR_DEALERS_ORDINARY.equals(black.getCarDealers())) {
                    // 普通车商进来
                    List<CommonCarDealer> list = carDealerService.list(Wrappers.<CommonCarDealer>query().lambda().eq(CommonCarDealer::getSocUniCrtCode, black.getIdCode()));
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            // 给数组里面加数据,并且只有在当时状态是  启用或者审核中
                            if (WitnessDic.STATUS_PASS.equals(list.get(i).getStatus()) || WitnessDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                                ids.add(list.get(i).getId());
                            }
                            BlacklistRelTemp relTemp = new BlacklistRelTemp();
                            relTemp.setBlacklistId(black.getId());
                            relTemp.setBlacklistTypeId(list.get(i).getId());
                            relTemp.setStatus(list.get(i).getStatus());
                            relTemp.setCreateBy(SecurityUtils.getUsername());
                            relTemp.setCreateTime(new Date(System.currentTimeMillis()));
                            blacklistRelTempService.save(relTemp);

                            // 修改表的状态
                            list.get(i).setStatus(BlackDic.STATUS_STOP);
                            carDealerService.updateById(list.get(i));
                            //停用关联表中关联关系
                            List<ChannelCoopeCardealerTemp> cardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                                    .eq(ChannelCoopeCardealerTemp::getCardealerId, list.get(i).getId().toString())
                                    .eq(ChannelCoopeCardealerTemp::getCardealerType, BlackDic.CAR_DEALERS_ORDINARY)
                            );
                            if (cardealerTemps.size() > 0) {
                                for (ChannelCoopeCardealerTemp temp : cardealerTemps) {
                                    temp.setStatus(BlackDic.STATUS_STOP);
                                    channelCoopeCardealerService.updateById(temp);
                                }
                            }
                        }
                        // 停用案件那边的信息状态
                        if (ids.size() > 0) {
                            result = channelUseCaseService.upStatusCarDealerByChannelIds(ids, headers);
                        }
                    }

                } else if (BlackDic.CAR_DEALERS_DIRECT.equals(black.getCarDealers())) {
                    // 直营车商进来
                    List<DirectCarDealer> list = directCarDealerService.list(Wrappers.<DirectCarDealer>query().lambda()
                            .eq(DirectCarDealer::getSocUniCrtCode, black.getIdCode())
                            .eq(DirectCarDealer::getChannelType, ChannelOnlineConstants.CHANNEL_TYPE_CAR_DEALERS));
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            BlacklistRelTemp relTemp = new BlacklistRelTemp();
                            relTemp.setBlacklistId(black.getId());
                            relTemp.setBlacklistTypeId(list.get(i).getId());
                            relTemp.setStatus(list.get(i).getChannelStatus());
                            relTemp.setChannelStatusOldCar(list.get(i).getChannelStatusOldCar());
                            relTemp.setCreateBy(SecurityUtils.getUsername());
                            relTemp.setCreateTime(new Date(System.currentTimeMillis()));
                            blacklistRelTempService.save(relTemp);


                            // 把这条信息停用
                            if (list.get(i).getChannelStatus() != null) {
                                list.get(i).setChannelStatus(BlackDic.STATUS_STOP);
                            }
                            if (list.get(i).getChannelStatusOldCar() != null) {
                                list.get(i).setChannelStatusOldCar(BlackDic.STATUS_STOP);
                            }
                            directCarDealerService.updateById(list.get(i));

                            //停用关联表中关联关系
                            List<ChannelCoopeCardealerTemp> cardealerTemps = channelCoopeCardealerService.list(Wrappers.<ChannelCoopeCardealerTemp>query().lambda()
                                    .eq(ChannelCoopeCardealerTemp::getCardealerId, list.get(i).getId().toString())
                                    .eq(ChannelCoopeCardealerTemp::getCardealerType, BlackDic.CAR_DEALERS_DIRECT)
                            );
                            if (cardealerTemps.size() > 0) {
                                for (ChannelCoopeCardealerTemp temp : cardealerTemps) {
                                    temp.setStatus(BlackDic.STATUS_STOP);
                                    channelCoopeCardealerService.updateById(temp);
                                }
                            }

                            // 给数组里面加数据
                            ids.add(list.get(i).getId());
                        }
                        // 再去案件那边去停用
                        if (ids.size() > 0) {
                            result = channelUseCaseService.upStatusByChannel(ids, headers);
                        }
                    }

                }


            }
            // 如果是通过 更新工作流
            SubmitDTO dto = new SubmitDTO();
            dto.setRegisterId(bb.getId());
            dto.setApprove("1");
            dto.setBizDataId(black.getDataId().toString());
            submit(dto);
            // 更新到名单库
            BlacklistTemp temp = blacklistTempService.getById(black.getId());
            BlackToListDTO btc = new BlackToListDTO();
            BlackDTO condition = new BlackDTO();
            condition.setStatus("1");
            // 赋值名单类型：合作商 01、挂靠单位 02、⻋商 05、⻅证⼈ 03、开票⽅ 04
            condition.setType(temp.getBlacklistType());
            condition.setName(temp.getBlackName());
            // 证件号码
            condition.setCertificateNo(temp.getIdCode());
            // 给证件类型（身份证 01、统⼀信⽤代码 02、纳税⼈识别号 03
            condition.setCertificateType(temp.getIdType());
            condition.setJoinTime(new Date(System.currentTimeMillis()));
            condition.setReason(temp.getBlacklistReason());
            condition.setApiUser("apiUser");
            // 仅车商可用⻋：商类型(1为普通⻋商2为直营⻋商)
            if (BlackDic.CAR_DEALERS_ORDINARY.equals(temp.getCarDealers())) {
                condition.setDealerType("1");
            } else if (BlackDic.CAR_DEALERS_DIRECT.equals(temp.getCarDealers())) {
                condition.setDealerType("2");
            }
            btc.setData(condition);
            JSONObject json = listBaseFeign.upBlackList(btc);
            if ("200".equals(json.get("code").toString())) {
                return IResponse.success("操作成功！").setData(json);
            } else {
                throw new AfsBaseException("更新名单库失败！");
            }

        }
        return IResponse.success("操作成功！").setData("");

    }

    @Transactional
    @PostMapping("/blackRelieveExamine")
    @ApiOperation(value = "黑名单解除审核")
    public IResponse blackRelieveExamine(@RequestBody BlacklistTemp black) throws JsonProcessingException {
        BlacklistTemp b = blacklistTempService.getById(black.getId());
        if (!BlackDic.STATUS_APPROVE.equals(b.getStatus())) {
            throw new AfsBaseException("信息已被审核！");
        }
        if (BlackDic.STATUS_REFUSE.equals(black.getStatus())) {
            BlacklistTemp temp = blacklistTempService.getById(black.getId());
            // 先结束工作流
            // 这边进来是拒绝
            SubmitDTO dto = new SubmitDTO();
            dto.setRegisterId(temp.getId());
            dto.setApprove("3");
            dto.setBizDataId(temp.getDataId().toString());
            submit(dto);

            temp.setStatus(BlackDic.STATUS_PASS);
            temp.setExamineStatus(BlackDic.EXAMINE_STATUS_PASS);
            blacklistTempService.updateById(temp);
            return IResponse.success("操作成功！").setData("");
        }
        // 查询这个黑名单的信息
        BlacklistTemp bb = blacklistTempService.getById(black);


        // 这个是只为见证人用的用于停系统账号
        List<ChannelCardDTO> upIds = new ArrayList<>();

        // 创建一个集合，存要修改的id
        List<Long> ids = new ArrayList<>();
        IResponse result = new IResponse();

        // 创建一个数据传输报头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());


        if (BlackDic.STATUS_PASS.equals(black.getStatus())) {
            // 第二部看看有没有关联关系
            List<BlacklistRelTemp> list = blacklistRelTempService.list(Wrappers.<BlacklistRelTemp>query().lambda().eq(BlacklistRelTemp::getBlacklistId, black.getId()));

            // 如何是合作商
            if (BlackDic.BLACKLIST_TYPE_PARTNER.equals(black.getBlacklistType())) {

                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ChannelBaseInfoTemp temp = channelOnlineService.getById(list.get(i).getBlacklistTypeId());
                        temp.setChannelStatus(list.get(i).getStatus());
                        temp.setChannelStatusOldCar(list.get(i).getChannelStatusOldCar());
                        channelOnlineService.updateById(temp);
                        // 只有以前的状态是 启用或者审核中才会去案件同步
                        if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getBlacklistTypeId());
                        }
                    }
                    // 去修改案件那边数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusByChannelPass(ids, headers);
                    }
                }
            }
            // 如果是挂靠单位
            if (BlackDic.BLACKLIST_TYPE_COMPANY.equals(black.getBlacklistType())) {
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ChannelAffiliatedUnitsTemp temp = channelAffiliatedUnitsTempService.getById(list.get(i).getBlacklistTypeId());
                        temp.setStatus(list.get(i).getStatus());
                        channelAffiliatedUnitsTempService.updateById(temp);
                        // 只有以前的状态是 启用或者审核中才会去案件同步
                        if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getBlacklistTypeId());
                        }
                    }
                    // 去修改案件那边数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upDateCaseStatusByIdsPass(ids, headers);
                    }
                }
            }
            // 如果是见证人
            if (BlackDic.BLACKLIST_TYPE_WITNESS.equals(black.getBlacklistType())) {
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ChannelWitnessInfoTemp temp = channelWitnessInfoTempService.getById(list.get(i).getBlacklistTypeId());
                        temp.setStatus(list.get(i).getStatus());
                        channelWitnessInfoTempService.updateById(temp);

                        ChannelCardDTO dto = new ChannelCardDTO();
                        dto.setCard(temp.getWitnessIdCard());
                        dto.setChannelId(temp.getChannelId());
                        upIds.add(dto);

                        // 只有以前的状态是 启用或者审核中才会去案件同步
                        if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                            ids.add(list.get(i).getBlacklistTypeId());
                        }
                    }
                    // 去修改案件那边数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusWitnessByChannelIdsPass(ids, headers);
                    }

                    // 被关掉的账号给启用了
                    Map<String, String> requestHeader = new HashMap<>();
                    requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
                    requestHeader.put("clientSecret", channelConfig.getApplyAdminClientSecret());
                    IResponse res = channelOnlineSyncService.startWitnessInfo(upIds, requestHeader);

                }
            }

            // 如果是开票方
            if (BlackDic.BLACKLIST_TYPE_BILLING.equals(black.getBlacklistType())) {
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        ids.add(list.get(i).getBlacklistTypeId());
                    }
                    // 去修改案件那边数据
                    if (ids.size() > 0) {
                        result = channelUseCaseService.upStatusDrawerByChannelIdsPass(ids, headers);
                    }
                }
            }


            // 如果是车商
            if (BlackDic.BLACKLIST_TYPE_CAR_DEALER.equals(black.getBlacklistType())) {
                // 判断是直营车商还是普通车商
                if (BlackDic.CAR_DEALERS_ORDINARY.equals(black.getCarDealers())) {
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            // 只有以前的状态是 启用或者审核中才会去案件同步
                            if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                                ids.add(list.get(i).getBlacklistTypeId());
                            }
                            CommonCarDealer temp = carDealerService.getById(list.get(i).getBlacklistTypeId());
                            temp.setStatus(list.get(i).getStatus());
                            carDealerService.updateById(temp);
                        }
                        // 去修改案件那边数据
                        if (ids.size() > 0) {
                            result = channelUseCaseService.upStatusCarDealerByChannelIdsPass(ids, headers);
                        }
                    }

                } else if (BlackDic.CAR_DEALERS_DIRECT.equals(black.getCarDealers())) {
                    // 这边是直营车商
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            ChannelBaseInfoTemp temp = channelOnlineService.getById(list.get(i).getBlacklistTypeId());
                            temp.setChannelStatus(list.get(i).getStatus());
                            temp.setChannelStatusOldCar(list.get(i).getChannelStatusOldCar());
                            channelOnlineService.updateById(temp);
                            // 只有以前的状态是 启用或者审核中才会去案件同步
                            if (BlackRelDic.STATUS_PASS.equals(list.get(i).getStatus()) || BlackRelDic.STATUS_APPROVE.equals(list.get(i).getStatus())) {
                                ids.add(list.get(i).getBlacklistTypeId());
                            }
                        }
                        // 去修改案件那边数据
                        if (ids.size() > 0) {
                            result = channelUseCaseService.upStatusByChannelPass(ids, headers);
                        }
                    }

                }

            }


            //最后把关系数据给删除
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    blacklistRelTempService.removeById(list.get(i).getId());
                }
            }

            // 更新名单库数据
            BlacklistTemp temp = blacklistTempService.getById(black.getId());
            BlackToListDTO btc = new BlackToListDTO();
            BlackDTO condition = new BlackDTO();
            condition.setStatus("2");
            // 赋值名单类型：合作商 01、挂靠单位 02、⻋商 05、⻅证⼈ 03、开票⽅ 04
            condition.setType(temp.getBlacklistType());
            condition.setName(temp.getBlackName());
            // 证件号码
            condition.setCertificateNo(temp.getIdCode());
            // 给证件类型（身份证 01、统⼀信⽤代码 02、纳税⼈识别号 03
            condition.setCertificateType(temp.getIdType());
            condition.setDeadTime(new Date(System.currentTimeMillis()));
            condition.setReason(temp.getRelieveReason());
            condition.setApiUser("apiUser");
            // 仅车商可用⻋：商类型(1为普通⻋商2为直营⻋商)
            if (BlackDic.CAR_DEALERS_ORDINARY.equals(temp.getCarDealers())) {
                condition.setDealerType("1");
            } else if (BlackDic.CAR_DEALERS_DIRECT.equals(temp.getCarDealers())) {
                condition.setDealerType("2");
            }
            btc.setData(condition);
            JSONObject json = listBaseFeign.upBlackList(btc);
            if ("200".equals(json.get("code").toString())) {
                return IResponse.success("操作成功！").setData(json);
            } else {
                throw new AfsBaseException("更新名单库失败！");
            }


        }
        // 去把工作流结束了
        SubmitDTO dto = new SubmitDTO();
        dto.setRegisterId(bb.getId());
        dto.setApprove("1");
        dto.setBizDataId(bb.getDataId().toString());
        submit(dto);
        //最后一步先更新这个黑名单的数据
//        black.setWeatherBlacklist(BlackDic.WEATHER_BLACKLIST_NO);
//        black.setBlackDate(new Date(System.currentTimeMillis()));
//        black.setExamineStatus(BlackDic.EXAMINE_STATUS_PASS);
//        black.setUpdateBy(SecurityUtils.getUsername());
//        black.setUpdateTime(new Date(System.currentTimeMillis()));
//        blacklistTempService.updateById(black);
        // 删除这个数据
        blacklistTempService.remove(Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getId, black.getId()));
        return IResponse.success("操作成功！");
    }

    @PostMapping("/checkBlackOnline")
    @ApiOperation(value = "渠道上线校验名单库")
    public Object checkBlackOnline(@RequestBody BlacklistTemp black) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (black.getBlacklistType() == "" || black.getBlacklistType() == null || black.getIdCode() == null || black.getIdCode() == "") {
                resultMap.put("weatherBlackList", BlackDic.WEATHER_BLACKLIST_NO);
                resultMap.put("code", "0000");
                resultMap.put("msg", "success");
                return resultMap;
            }else{
                BlackDTO condition = new BlackDTO();
                condition.setPageNum(1);
                condition.setPageSize(10);
                condition.setCertificateNo(black.getIdCode());
                condition.setType(black.getBlacklistType());
                condition.setStatus(TYPE_YES);
                JSONObject json = listBaseFeign.getBlackList(condition);

                if ("200".equals(json.get("code").toString())) {
                    Integer total = json.getInteger("total");
                    if (total > 0) {
                        resultMap.put("weatherBlackList", BlackDic.WEATHER_BLACKLIST_YES);
                    } else {
                        resultMap.put("weatherBlackList", BlackDic.WEATHER_BLACKLIST_NO);
                    }
                    resultMap.put("code", "0000");
                    resultMap.put("msg", "success");
                }
            }
        } catch (Exception e) {
            resultMap.put("code", "9999");
            resultMap.put("msg", "查询失败，请联系管理员！");
            logger.error(e.getMessage(), e);
        }
        return resultMap;
    }
}
